package com.kasax.sample.okhttp;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class AppMain {

    private static Call call;

    public static void main(String[] args) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .callTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();
        Request request = new Request.Builder()
                .url("https://wanandroid.com/harmony/index/json\n")
                .get().build();
        call = okHttpClient.newCall(request);
//        testEecute();
        testAsyncExecute();
    }

    private static void testAsyncExecute() {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logResult(response);
            }
        });
    }

    private static void testEecute() {
        try {
            Response response = call.execute();
            logResult(response);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    private static void logResult(Response response) throws IOException {
        String data = response.body().string();
        System.out.println(data);
    }
}